package com.itany.book.book.service.impl;

import com.itany.book.book.dao.BookMapper;
import com.itany.book.book.service.IBookService;
import com.itany.book.pojo.Book;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by tyh on 2018/9/23.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service
public class BookServiceImpl implements IBookService {


    //如果爆红，是因为BookMapper只有interface，没有实现类
    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private HttpSolrClient solrClient;

    @Override
    public void addDoc() {
        List<Book> books = bookMapper.selectAllBooks(null);
        try {
            for (Book book:books){
                SolrInputDocument doc = new SolrInputDocument();
                doc.addField("id", book.getId());
                doc.addField("bookname", book.getBookname());
                doc.addField("imgurl", book.getImgurl());
                doc.addField("pressName", book.getPressName());
                String date = new SimpleDateFormat("yyyy-MM-dd").format(book.getPublishdate());
                doc.addField("publishdate",date);
                doc.addField("bookintroduce", book.getBookintroduce());
                doc.addField("price", book.getPrice());
                doc.addField("author", book.getAuthor());
                solrClient.add(doc);
            }
            solrClient.commit();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                solrClient.rollback();
            } catch (Exception e1) {
            }
        }
    }

    @Override
    public Map<String, Object> findDoc(String keyword, Integer pageNo, int pageSize) {
        Map<String, Object> pageInfo = new HashMap();
        List<Book> books = new ArrayList<>();
        // List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        System.out.println("keyword:"+keyword);
        System.out.println(keyword.length());
        try {
            String q = "bookname:"+keyword+" OR pressName:"+keyword+" OR bookintroduce: "+keyword + " OR author: "+keyword;
            if (keyword == null || keyword=="" ||  keyword.length()==0){
                q="*:*";
            }
            System.out.println("---------");
            System.out.println(q);
            SolrQuery solrQuery = new SolrQuery();
            solrQuery.setQuery(q);
            solrQuery.setHighlight(true);
            solrQuery.setStart((pageNo - 1) * pageSize);
            solrQuery.setRows(pageSize);
            //solrQuery.setStart((pageNo-1)*pageSize);
            //solrQuery.setRows(pageSize);
            solrQuery.setHighlightSimplePre("<font color='red'>");
            solrQuery.setHighlightSimplePost("</font>");
            solrQuery.setParam("hl.fl", "*");
            QueryResponse response = solrClient.query(solrQuery);

            SolrDocumentList result = response.getResults();
            System.out.println("count(*)============" + result.getNumFound());
            pageInfo.put("numFound", result.getNumFound());
            for (int i = 0; i < result.size(); i++) {
                Book book = new Book();
                // Map<String, String> vo = new HashMap<String, String>();
                SolrDocument sdoc = result.get(i);
                String id = (String) sdoc.get("id");
                //获取高亮后的数据
                Map<String, List<String>> map = response.getHighlighting().get(id);
                // 1. 获取高亮的bookname
                List<String> booknameList = map.get("bookname");
                if (booknameList != null) {
                    book.setBookname(booknameList.get(0));
                } else {
                    book.setBookname((String) sdoc.get("bookname"));
                }
                // 2 获取高亮的pressName
                List<String> pressNameList = map.get("pressName");
                if (pressNameList != null) {
                    book.setPressName(pressNameList.get(0));
                } else {
                    book.setPressName((String) sdoc.get("pressName"));
                }
                // 3 获取高亮的bookintroduce
                List<String> bookintroduceList = map.get("bookintroduce");
                if (bookintroduceList != null) {
                    book.setBookintroduce(bookintroduceList.get(0));
                } else {
                    book.setBookintroduce((String) sdoc.get("bookintroduce"));
                }
                // 4 获取高亮的author
                List<String> authorList = map.get("author");
                if (authorList != null) {
                    book.setAuthor(authorList.get(0));
                } else {
                    book.setAuthor((String) sdoc.get("author"));
                }
                book.setImgurl((String) sdoc.get("imgurl"));
                Date dd = new SimpleDateFormat("yyyy-MM-dd").parse((String) sdoc.get("publishdate"));
                book.setPublishdate(dd);
                book.setPrice(Double.parseDouble((String)sdoc.get("price")));
                books.add(book);
            }
            pageInfo.put("list", books);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    @Override
    public List<Book> findAllBooks(String lastType) {
        return bookMapper.selectAllBooks(lastType);
    }

    @Override
    public Book findById(Integer id) {
        return bookMapper.selectById(id);
    }
}
